import { View, Text, Button, Checkbox, CheckboxGroup, Image, Input } from '@tarojs/components'
import { useState } from 'react'
import Taro from '@tarojs/taro'
import api from '../../axios/loginaxios/request'
import { useAuth } from '../../contexts'
import './login.scss'

export default function Login() {
    const { login } = useAuth()
    const [agreeProtocol, setAgreeProtocol] = useState<boolean>(false)
    const [showAuthModal, setShowAuthModal] = useState<boolean>(false)
    const [avatarUrl, setAvatarUrl] = useState<string>('')
    const [nickname, setNickname] = useState<string>('')

    // 处理协议同意状态变化
    const handleProtocolChange = (e) => {
        setAgreeProtocol(e.detail.value.includes('agree'))
    }

    // 一键登录 - 弹出授权模态框
    const handleOneClickLogin = () => {
        // 检查用户协议同意状态
        if (!agreeProtocol) {
            Taro.showToast({
                title: '请先同意用户协议',
                icon: 'none'
            })
            return
        }

        // 弹出授权模态框
        setShowAuthModal(true)
    }

    // 处理用户授权 - 使用用户填写的信息进行登录
    const handleUserAuth = async () => {
        try {
            // 验证用户是否填写了必要信息
            if (!nickname.trim()) {
                Taro.showToast({
                    title: '请输入昵称',
                    icon: 'none'
                })
                return
            }

            // 显示加载中
            Taro.showLoading({
                title: '登录中...'
            })

            // 获取微信登录code
            const loginRes = await Taro.login()

            if (!loginRes.code) {
                throw new Error('获取微信登录码失败')
            }

            // 关闭模态框
            setShowAuthModal(false)

            // 构造用户信息
            const userInfo = {
                nickName: nickname.trim(),
                avatarUrl: avatarUrl || '',
            }


            // 调用后端API进行微信登录，包含用户信息
            const response: any = await api.post('/auth/wechat-login', {
                code: loginRes.code,
                agreeProtocol: true,
                userInfo: userInfo
            })

            if (response.success) {
                // 使用全局状态管理保存用户信息和token
                if (response.token && response.userInfo) {
                    login(response.userInfo, response.token)
                }

                Taro.showToast({
                    title: '登录成功',
                    icon: 'success'
                })

                // 延迟跳转到首页
                setTimeout(() => {
                    Taro.switchTab({
                        url: '/pages/index/index'
                    }).catch((error) => {
                        console.log('跳转失败，使用重定向:', error)
                        // 如果switchTab失败，使用redirectTo
                        Taro.redirectTo({
                            url: '/pages/index/index'
                        })
                    })
                }, 1500)
            } else {
                throw new Error(response.message || '登录失败')
            }

        } catch (error: any) {
            console.error('微信登录失败:', error)
            setShowAuthModal(false)

            Taro.showToast({
                title: error.message || '登录失败，请重试',
                icon: 'none'
            })
        } finally {
            Taro.hideLoading()
        }
    }

    // 关闭授权模态框
    const handleCloseAuthModal = () => {
        setShowAuthModal(false)
        setAvatarUrl('')
        setNickname('')
    }

    // 选择头像
    const handleChooseAvatar = (e) => {
        const { avatarUrl } = e.detail
        setAvatarUrl(avatarUrl)
    }

    // 输入昵称
    const handleNicknameInput = (e) => {
        const { value } = e.detail
        setNickname(value)
    }

    // 手机号登录
    const handlePhoneLogin = () => {
        if (!agreeProtocol) {
            Taro.showToast({
                title: '请先同意用户协议',
                icon: 'none'
            })
            return
        }

        Taro.navigateTo({
            url: '/pages/phone-login/phone-login'
        })
    }

    // 查看协议
    const handleViewProtocol = (type) => {
        const title = type === 'user' ? '用户协议' : '隐私政策'
        Taro.showToast({
            title: `查看${title}`,
            icon: 'none'
        })
    }


    return (
        <View className="login-container">
            {/* Logo区域 */}
            <View className="logo-section">
                <View className="logo">
                    <Text className="logo-text">新氧</Text>
                </View>
            </View>

            {/* 协议同意区域 */}
            <View className="protocol-section">
                <CheckboxGroup onChange={handleProtocolChange}>
                    <View className="checkbox-wrapper">
                        <Checkbox
                            value="agree"
                            checked={agreeProtocol}
                            className="protocol-checkbox"
                        />
                        <Text className="protocol-text">
                            我已阅读并同意
                            <Text
                                className="protocol-link"
                                onClick={() => handleViewProtocol('user')}
                            >
                                《新氧用户协议》
                            </Text>
                            及
                            <Text
                                className="protocol-link"
                                onClick={() => handleViewProtocol('privacy')}
                            >
                                《隐私政策》
                            </Text>
                        </Text>
                    </View>
                </CheckboxGroup>
            </View>

            {/* 登录按钮区域 */}
            <View className="login-buttons">
                <Button
                    className="one-click-btn active"
                    onClick={handleOneClickLogin}
                >
                    一键登录
                </Button>

                <Text
                    className="phone-login-text"
                    onClick={handlePhoneLogin}
                >
                    手机号登录
                </Text>
            </View>

            {/* 底部提示 */}
            <View className="bottom-tip">
                <Text className="tip-text">未注册手机号将创建新氧账号</Text>
            </View>

            {/* 用户授权模态框 */}
            {showAuthModal && (
                <View className="auth-modal-overlay">
                    <View className="auth-modal">
                        <View className="auth-modal-header">
                            <Text className="auth-modal-title">新氧安心美</Text>
                            <Text className="auth-modal-subtitle">申请</Text>
                            <View
                                className="auth-modal-close"
                                onClick={handleCloseAuthModal}
                            >
                                ×
                            </View>
                        </View>

                        <View className="auth-modal-content">
                            <Text className="auth-modal-phone">获取你的昵称、头像</Text>
                            <Text className="auth-modal-phone-number">用于完善个人资料</Text>
                            <Text className="auth-modal-desc">为了给您提供更好的服务</Text>

                            {/* 头像昵称填写组件 */}
                            <View className="profile-form">
                                <View className="avatar-section">
                                    <Button
                                        className="avatar-button"
                                        openType="chooseAvatar"
                                        onChooseAvatar={handleChooseAvatar}
                                    >
                                        {avatarUrl ? (
                                            <Image
                                                className="avatar-image"
                                                src={avatarUrl}
                                            />
                                        ) : (
                                            <View className="avatar-placeholder">
                                                <Text className="avatar-placeholder-text">👤</Text>
                                            </View>
                                        )}
                                        <Text className="avatar-text">选择头像</Text>
                                    </Button>
                                </View>
                                <View className="nickname-section">
                                    <Input
                                        className="nickname-input"
                                        type="nickname"
                                        placeholder="请输入昵称"
                                        value={nickname}
                                        onInput={handleNicknameInput}
                                        maxlength={10}
                                    />
                                </View>
                            </View>
                        </View>

                        <View className="auth-modal-buttons">
                            <Button
                                className="auth-btn-allow"
                                onClick={handleUserAuth}
                            >
                                确认并登录
                            </Button>
                            <Button
                                className="auth-btn-cancel"
                                onClick={handleCloseAuthModal}
                            >
                                取消
                            </Button>
                        </View>
                    </View>
                </View>
            )}
        </View>
    )
}